@tool
extends Control

#region 属性
@onready var _add_section:Control = %AddSection
@onready var _no_option_label:Control = %NoOptionsLabel
@onready var _add_node_name_line_edit:LineEdit = %AddNodeNameLineEdit
@onready var _add_grid_container:Control = %AddGridContainer
var _selected_node:Node
var _editor_interface:EditorInterface
var _undo_redo:EditorUndoRedoManager
#endregion
#region 字段
#endregion
#region 信号
signal  sidebar_toggle_requested()
#endregion

#region 基类方法
#endregion
#region 公共方法
func setup(editor_interface:EditorInterface,undo_redo:EditorUndoRedoManager):
	_editor_interface = editor_interface
	_undo_redo = undo_redo
func change_selected_node(node):
	_selected_node = node
	_repaint()
#endregion
#region 私有方法
func _repaint():
	var can_add_states = (_selected_node is StateChart and _selected_node.get_child_count() == 0) or _selected_node is State_Compound or _selected_node is State_Parallel
	var can_add_transitions = _selected_node is State
	_add_section.visible = can_add_states or can_add_transitions
	_no_option_label.visible = not _add_section.visible
	for btn in _add_grid_container.get_children():
		if btn.name.begins_with("State_"):
			btn.visible = can_add_states
		elif btn.name.begins_with("Tran_"):
			btn.visible = can_add_transitions
func _create_node(type,name:StringName):
	var final_name = _add_node_name_line_edit.text.strip_edges()
	if final_name.length() == 0:
		final_name = name
	var new_node = type.new()
	_undo_redo.create_action("Add " + final_name)
	_undo_redo.add_do_method(_selected_node,"add_child",new_node)
	_undo_redo.add_undo_method(_selected_node,"remove_child",new_node)
	_undo_redo.add_do_reference(new_node)
	_undo_redo.add_do_method(new_node,"set_owner",_selected_node.get_tree().edited_scene_root)
	_undo_redo.add_do_property(new_node,"name",final_name)
	_undo_redo.commit_action()
	
	if Input.is_key_pressed(KEY_SHIFT):
		_editor_interface.get_selection().clear()
		_editor_interface.get_selection().add_node(new_node)
	
	_add_node_name_line_edit.grab_focus()
	_editor_interface.edit_node(new_node)
	_repaint()
func _on_atomic_state_pressed():
	_create_node(State_Atomic, "State_Atomic")
func _on_compound_state_pressed():
	_create_node(State_Compound, "CompoundState")
func _on_parallel_state_pressed():
	_create_node(State_Parallel, "ParallelState")
func _on_history_state_pressed():
	_create_node(State_History, "HistoryState")
func _on_transition_pressed():
	_create_node(Transition, "Transition")
func _on_animation_tree_state_pressed():
	#_create_node(State_AnimationTree, "State_AnimationTree")
	# TODO 暂时不需要先不实现
	pass
func _on_animation_player_state_pressed():
	_create_node(State_AnimationPlayer, "State_AnimationPlayer")
func _on_toggle_sidebar_button_pressed():
	sidebar_toggle_requested.emit()
#endregion
#region 生命周期函数
#endregion
